define(['app','datetime','js/directive/listTree', 'js/filter/tree2Arr','highcharts','exporting','autocomplete','pagination'], function( app ) {
  'use strict';
  /*呼叫控制系统配置*/
  app.controller('Om', function($scope, dataFactoryCRM, $q,$compile) {
    $scope.calllog;
    $scope.calllogpage = {
      pageAll: 1,
      pageNow: 1,
      pageSize: $scope.psize,
      k: 11
    };
    $scope.OMs=[{}];
    $scope.s_OMS2='';
    $scope.sty;
    $scope.clerkname;
    $scope.extnum_ng;

    /*系统错误调用*/
    $scope.msgAttention = function() {
          $('.ui.systemerror').modal({
              closable: true,
              onDeny: function() {
                  return true;
              },
              onApprove: function() {
                  $('.ui.dimmer.modals.page.transition.visible.active.dimmers').removeClass('dimmers');
              }
          }).modal('show');
        setTimeout(function() {
            var system = $('.ui.dimmer.modals.page.transition.visible.active');
            if (system) {
                $('.ui.dimmer.modals.page.transition.visible.active').addClass('dimmers');
            }
        }, 1000);
    }

    /*获取登录用户信息*/
    $scope.userInfo = function() {
        /*get user sectors*/
        var _url = 'sector/index';
        dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
            if (_d.rcode)
                $scope.SectorTree = _d.data;
              // console.log(_d.data);
        });
    };
    $scope.userInfo();

    //话务管理 
    $scope.getCallogList = function(d) {
      $scope.$emit("BUSY");
      var callnum = $('#callnum').val();
      var callTime = $('#createtime').val();
      var calltimend = $('#endtime').val();
      var _url = 'Om/index?p=' + $scope.calllogpage.pageNow + '&psize=' + $scope.calllogpage.pageSize +'&verify='+ $scope.cus+'&day='+d;
      var conn = '&sector='+ callnum +'&phonenum='+$scope.phonenum+'&createtime='+$scope.createtimeextlist+'&endtime='+$scope.endtimeextlist+'&type='+$scope.type +'&clerkname='+ $scope.clerkname;
      var url = _url + conn;
      dataFactoryCRM.getDataByAPI(url).then(function(_d) {      
           //console.log(_d);
        if (_d.rcode == 1) {
          $scope.calllogpage.pageSize = _d.psize;
          $scope.calllogpage.pageAll = _d.pall;
          $scope.calllogpage.pageNow = _d.p;
          $scope.calllog = _d.data;
        } else {
          $scope.calllogpage.pageAll = 0;       
        }
        $scope.$emit("NOTBUSY");
      });

      $scope.busy = dataFactoryCRM.getDataByAPI('Om/getsector')
              .then( function( data ) {
                $scope.busy = false;
               // console.log(data);
                    if( data ) { 
                        $scope.sectors = data.psector; 
                        $scope.sectormain = data.psector;
                        $scope.sectorphone = data.psector;
                    }
              });
    }

    $scope.totally = function(){
    $scope.cus = 0;
      $("#demo1").addClass("selected");
      $("#demo2").removeClass("selected");
      $("#demo3").removeClass("selected");
      $scope.getCallogList();
    } 

    $scope.totally();
    $scope.myCom = function(){
    $scope.cus = 1;
      $("#demo2").addClass("selected");
      $("#demo1").removeClass("selected");
      $("#demo3").removeClass("selected");
      $scope.getCallogList();
    } 

    $scope.otherCom = function(){
    $scope.cus = 2;
      $("#demo3").addClass("selected");
      $("#demo1").removeClass("selected");
      $("#demo2").removeClass("selected");
      $scope.getCallogList();
    } 

   // 话务管理
   $scope.second = function(){
    $scope.getCallogList();
   }

   // OM配置
    $scope.third = function(){
      $scope.getOmList();
    }


  // 分机配置
   $scope.forth = function(){
      $scope.OmDataList(0);
      dataFactoryCRM.getDataByAPI('Om/getdevice')
      .then( function( data ) {
            if( data ) { 
              // console.log(data);
               $scope.OMc = data; 
            }
      });
   }


  // OM管理
    $scope.getOmList = function() {
      $scope.$emit("BUSY");
      var _url = 'Om/getOmlist?p=' + $scope.calllogpage.pageNow + '&psize=' + $scope.calllogpage.pageSize;
      dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
        //console.log(_d);
        if (_d.rcode == 1) {
          $scope.calllogpage.pageSize = _d.psize;
          $scope.calllogpage.pageAll = _d.pall;
          $scope.calllogpage.pageNow = _d.p;
          $scope.calllogOM = _d.data;
        } else {
          $scope.calllogpage.pageAll = 0;     
        }
        $scope.$emit("NOTBUSY");
      });
    }
    
    // OM添加
    $scope.AddConfig=function(){
          $('.ui.add.modal').modal({
              onApprove: function() {
                if( $('#OMid').form('is valid') ){
                    $scope.addChannal( $('#OMid').serialize());
                    return true;
                  }
                  else
                      return false;           
              }}).modal('show');   
    }


   //OM添加 
    $scope.addChannal = function(_d){
      // $scope.$emit("BUSY");
      $scope.busy = dataFactoryCRM.postDataByAPI('Om/addOm', _d)
              .then(function(d){
                //console.log(d);
                $scope.omrcode = d.rcode;
              if( d.rcode ) {
                $('#OMid input').val('');
                if( $scope.calllogOM )
                  $scope.calllogOM.splice(0,0, d.data );
                else{
                  $scope.calllogOM = new Array();
                  $scope.calllogOM.push( d.data );
                }
                return true;
              }else{
                    // $scope.$emit("NOTBUSY");
                    $scope.omMsg = d.msg;
                    $scope.msgAttention();
                    return false;
                }
                // $scope.$emit("NOTBUSY");
             });
    } 


   // OM编辑
    $scope.editOM = function(){
      var _calOM = this.calOM;
      $('#omid').val(_calOM.omid);
      $('#add_name1').val(_calOM.name);
      $('#add_address1').val(_calOM.ipaddr);
      $('#add_IPPBX1').val(_calOM.serverip);
      $('#port1').val(_calOM.serviceport);
      $('#add_record1').val(_calOM.mp3_server);
      $('#add_list1').val(_calOM.mp3_dir);
      $('#add_Ads1').val(_calOM.dbhost);
      $('#add_port1').val(_calOM.dbport);
      $('#add_cname1').val(_calOM.dbuser);
      $('#database1').val(_calOM.dbname);
      $('#add_pass1').val(_calOM.dbpsw);
      $('.ui.edit.modal').modal({
          onApprove: function() { 
            $scope.$emit("BUSY");
            if( $('#eidtOMid').form('is valid') ){
               dataFactoryCRM.postDataByAPI('Om/editom',$('#eidtOMid').serialize())
              .then(function(d){
                $scope.omrcode = d.rcode;
                   if (d['rcode']=="1") {
                      if( $scope.calllogOM ){
                        var i = 0;
                        for(;i<$scope.calllogOM.length; i++){
                          if( $scope.calllogOM[i].omid == _calOM.omid){//返回的数据是所有的数据，让后逐行遍历。修改完之后，直接从前边显示出来；
                            $scope.calllogOM[i] = d.data;
                            break;
                          }
                        }
                      }
                  }else{
                    $scope.$emit("NOTBUSY");
                    $scope.omMsg = d.msg;
                    $scope.msgAttention();
                }
                $scope.$emit("NOTBUSY");
              });                       
              return true;
            }else{
              return false;
            }
          }}).modal('show'); 
    }

    // 分机配置
      dataFactoryCRM.getDataByAPI('Om/getOM')
      .then( function( data ) {
            if( data ) { 
              $scope.OMs = data; 
            }
      });

    $scope.Omtypepass = function( _type,_type1 ){
          for(var i=0;i<$scope.OMs.length;i++){
              if( _type != i )
                  $scope.OMs[i]['cs'] = '';
              else{
                  if(  $scope.OMs[i]['cs'] == 'active' ){
                      $scope.s_OMS2 = 0;
                      $scope.OMs[i]['cs'] = ''
                  }
                  else{
                      $scope.OMs[i]['cs'] = 'active';
                      $scope.s_OMS2 = _type1;
                  }
              }
          }
          $scope.OmDataList();
    }

  $scope.subphones;
  $scope.paypersons;
   //分机配置 
    $scope.OmDataList = function(type) {
      // $scope.$emit("BUSY");
      if(type == 0) $scope.OMs[0]['cs'] = 'active';
      if(type) $scope.s_OMS2 = type;
      var paypersons = $('#paypersons').val();
      var subphones = $('#subphones').val();
      var sectoradd = $('#extadd').val();
      //console.log(sectoradd);
      var _url = 'Om/OMlist?p=' + $scope.calllogpage.pageNow + '&psize=' + $scope.calllogpage.pageSize;
       _url = _url + '&type='+ $scope.s_OMS2 +'&subphones='+ subphones +'&paypersons='+ paypersons+'&sectoradd='+ sectoradd;

      dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
          if (_d.rcode=="1") {
            $scope.calllogpage.pageSize = _d.psize;
            $scope.calllogpage.pageAll = _d.pall;
            $scope.calllogpage.pageNow = _d.p;
            $scope.Omtrans = _d.data;
          } else {
            $scope.calllogpage.pageAll = 0;
          }
          // $scope.$emit("NOTBUSY");
      });

    }

    $scope.OmDataList(0);

    // 获得员工
      dataFactoryCRM.getDataByAPI('om/getclerk').then(function(_d) {
            $scope.getnum = _d;
      });

    // 分机配置添加
    $scope.addConfig=function(){
          $('.ui.om.modal').modal({
              onApprove: function() {
                if( $('#addID').form('is valid') ){
                    $scope.addom();
                    return true;
                  }
                  else
                      return false;           
              }}).modal('show');   
    }


    // 分机配置添加 
    $scope.addom = function(){
          // $scope.$emit("BUSY");
         dataFactoryCRM.getDataByAPI('Om/addOmconfig?bindperson=' + $('#bindperson_value').val()+'&subtelphone='+$('#subtelphone').val()+'&add_device='+$('#add_device').val())
              .then(function(d){
                $scope.omrcode = d.rcode;
              if( d.rcode ) {
                $('#addID input').val('');
                if( $scope.Omtrans )
                  $scope.Omtrans.splice(0,0, d.data );
                else{
                  $scope.Omtrans = new Array();
                  $scope.Omtrans.push( d.data );
                }
                return true;
              }else{
                  // $scope.$emit("NOTBUSY");
                  $scope.omMsg = d.msg;
                  $scope.msgAttention();
                  return false;
              }
              // $scope.$emit("NOTBUSY");
             });
    }

    // 分机配置编辑
    $scope.editphone = function(){
      var _vom = this.vom;
      // console.log(_vom);
      $('#bindperson1').val(_vom.nickname);
      $('#subtelphone1').val(_vom.subphone);
      $('#add_device1').val(_vom.omid);
      $('#default_om').text(_vom.name);
      $('#subid').val(_vom.id);

      $('.ui.om1.modal').modal({
          onApprove: function() { 
            $scope.$emit("BUSY");
            if( $('#editID').form('is valid') ){
               dataFactoryCRM.postDataByAPI('Om/editphone',$('#editID').serialize())
              .then(function(d){
                // console.log(d);
                   if (d['rcode']=="1") {
                      if( $scope.Omtrans ){
                        var i = 0;
                        for(;i<$scope.Omtrans.length; i++){
                          if( $scope.Omtrans[i].id == _vom.id){
                            $scope.Omtrans[i] = d.data;
                            break;
                          }
                        }
                      }
                  }else{
                      $scope.$emit("NOTBUSY");
                      $scope.omMsg = d.msg;
                      $scope.msgAttention();
                  }
                  $scope.$emit("NOTBUSY");
              });                       
              return true;
            }else{
              return false;
            }
          }}).modal('show'); 
    }

    // 时长统计折线图
    $scope.searchext = function(){
      var sector = $("#extnum").val();
      var starttime = $('#createtimeext').val();
      var endtime = $('#endtimeext').val();
      var _urls = 'Om/getcalmsg?sector='+ $('#extnum').val() +'&ext_id='+ $scope.extid +'&starttime='+starttime +'&endtime=' +endtime +'&sty='+ $scope.sty;
      dataFactoryCRM.getDataByAPI(_urls)
      .then( function( data ) {
            if( data ) { 
              if (data.sector_name) {
                if (data.sector_id == 1) {
                  $('#extnum_id').text('全部');
                }else{
                  $('#extnum_id').text(data.sector_name);
                }
                $('#container').highcharts({
                    chart: {
                        type: 'bar',
                        height:500
                    },
                    title: {
                        text: '时长统计(单位:分钟)'
                    },
                    xAxis: {
                        categories: data.sector_name,
                        title: {
                            text: '部门名称'
                        }
                    },
                    yAxis: {
                        min: 0,
                        title: {
                            text: 'time (minutes)',
                            align: 'high'
                        },
                        labels: {
                            overflow: 'justify'
                        }
                    },
                    tooltip: {
                        valueSuffix: ' minutes'
                    },
                    plotOptions: {
                        bar: {
                            dataLabels: {
                                enabled: true
                            }
                        }
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -40,
                        y: 5,
                        floating: true,
                        borderWidth: 1,
                        backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                        shadow: true
                    },
                    credits: {
                        enabled: false
                    },
                    series: [{
                        name: '通话时长',
                        data: data.timelong
                    }]
                });              
              }else{
                if (data.sector_id == 1) {
                  $('#extnum_id').text('全部');
                }else{
                  $('#extnum_id').text(data.sector_name);
                }
                $('#container').highcharts({
                    chart: {
                        type: 'bar',
                        height:900
                    },
                    title: {
                        text: '时长统计(单位:分钟)'
                    },
                    xAxis: {
                        categories: data.nickname,
                        title: {
                            text: '员工姓名'
                        }
                    },
                    yAxis: {
                        min: 0,
                        title: {
                            text: 'time (minutes)',
                            align: 'high'
                        },
                        labels: {
                            overflow: 'justify'
                        }
                    },
                    tooltip: {
                        valueSuffix: ' minutes'
                    },
                    plotOptions: {
                        bar: {
                            dataLabels: {
                                enabled: true
                            }
                        }
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -40,
                        y: 5,
                        floating: true,
                        borderWidth: 1,
                        backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                        shadow: true
                    },
                    credits: {
                        enabled: false
                    },
                    series: [{
                        name: '通话时长',
                        data: data.timelong
                    }]
                });              
              }
            }
      });    
    }

    // $scope.searchext();

    $scope.persondisplay = function(){
    $scope.sty = 1;
      $("#sty1").addClass("blue");
      $("#sty2").removeClass("blue");
      $scope.searchext();
    } 

    $scope.sectordisplay = function(){
    $scope.sty = 2;
      $("#sty2").addClass("blue");
      $("#sty1").removeClass("blue");
      $scope.searchext();
    } 

    $scope.sectordisplay();//方法要放到定义后边

  });

});
